<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author paulaan
 */

namespace Vietland\UserBundle\Document;

use FOS\UserBundle\Document\User as BaseUser;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Vietland\AdsBundle\Document\Avatar;
use Doctrine\ODM\MongoDB\MongoDBException;

/**
 * @MongoDB\Document(db="esite", collection="users")
 */
class User extends BaseUser {

    /**
     * @MongoDB\Id(strategy="increment")
     */
    protected $id;

    /**
     *
     * @MongoDB\String
     */
    protected $sex;

    /**
     *
     * @MongoDB\date
     */
    protected $dob;

    /**
     * @MongoDB\boolean
     */
    protected $cropped;

    /**
     * @MongoDB\ReferenceMany(targetDocument="Group")
     */
    protected $groups = array();

    /**
     * @MongoDB\ReferenceMany(targetDocument="Vietland\AdsBundle\Document\Post", mappedBy="user")
     */
    protected $posts;

    /**
     *
     * @MongoDB\ReferenceMany(targetDocument="Vietland\AdsBundle\Document\Avatar", inversedBy="user")
     */
    protected $avatars;
    private $dm;

    public function __construct() {
        parent::__construct();
        $this->cropped = false;
        $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
        $this->avatars = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getAvatars($size = 0) {
        foreach ($this->avatars->toArray() as $avatar) {
            if ($avatar->getSize() == $size) {
                return $avatar;
            }
        }
        return null;
    }

    public function setAvatars($avatar) {
        if ($this->avatars === NULL)
            $this->avatars = new \Doctrine\Common\Collections\ArrayCollection();
        if (is_object($avatar)) {
            $db = new \Mongo('mongodb://127.0.0.1:27017');
            if ($oldbig = $this->getAvatars(Avatar::AVATAR_LARGE)) {
                $this->avatars->removeElement($oldbig);
                $db->selectDB("vietland")->selectCollection("Avatar.files")->remove(array('_id'=> $oldbig->getId()), array('fsync' => true));
                $db->selectDB("vietland")->selectCollection("Avatar.chunks")->remove(array('files_id' => $oldbig->getId()),array('fsync' => true));
            }
            
            $big = new Avatar();
            $big->setSize(Avatar::AVATAR_LARGE);
            $this->avatars->add($big);
            $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $avatar->getClientOriginalName());
            $avatar->move(__DIR__ . '/../../../../web/tmp/', $this->getUsername() . '.' . $ext);
            $image = __DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $ext;
            $width = $this->getWidth($image);
            $height = $this->getHeight($image);
            if ($width > 500) {
                $scale = 500 / $width;
                $uploaded = $this->resizeImage($image, $width, $height, $scale);
            } else {
                $scale = 1;
                $uploaded = $this->resizeImage($image, $width, $height, $scale);
            }
            $big->setFile(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $ext);
            $big->setExt($ext);

            $this->dm->persist($big);
            $this->dm->persist($this);
            $this->dm->flush();
        }
    }

    public function setDm($dm) {
        $this->dm = $dm;
    }

    public function getAvatarFile() {
        $big = null;
        $big = $this->getAvatars(Avatar::AVATAR_LARGE);
        if (is_object($big) && $big instanceof Avatar) {
            try {
                $image = imagecreatefromstring($big->getFile()->getBytes());
                imagejpeg($image, __DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $big->getExt());
                return 'http://vietland.piv/tmp/' . $this->getUsername() . '.' . $big->getExt();
            } catch (MongoDBException $e) {
                return 'http://vietland.piv/tmp/noavatar.png';
            }
        } else
            return 'http://vietland.piv/tmp/noavatar.png';
    }

    public function getAvatarWidth() {
        if ($this->getAvatars(Avatar::AVATAR_LARGE) instanceof Avatar && file_exists(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt()))
            return $this->getWidth(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt());
        else
            return 0;
    }

    public function getAvatarHeight() {
        if ($this->getAvatars(Avatar::AVATAR_LARGE) instanceof Avatar && file_exists(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt()))
            return $this->getHeight(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt());
        else
            return 0;
    }

    public function getCropped() {
        return $this->cropped;
    }

    public function setCropped($cropped = false) {
        $cropped = explode('-', $cropped);
        $dm = $this->dm;
        if (is_array($cropped) && count($cropped) == 6 && $this->getAvatars(Avatar::AVATAR_LARGE)) {
            foreach ($this->avatars->toArray() as $oldsmall) {
                if ($oldsmall->getSize() == Avatar::AVATAR_SMALL) {
                    $this->avatars->removeElement($oldsmall);
                    $this->dm->remove($oldsmall);
                }
            }
            $small = new Avatar();
            $small->setSize(Avatar::AVATAR_SMALL);
            $this->avatars->add($small);
            $image = imagecreatefromstring($this->getAvatars(Avatar::AVATAR_LARGE)->getFile()->getBytes());
            imagejpeg($image, __DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt());
            $imagesource = __DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt();
            $x1 = $cropped[0];
            $y1 = $cropped[1];
            $x2 = $cropped[2];
            $y2 = $cropped[3];
            $w = $cropped[4];
            $h = $cropped[5];
            //Scale the image to the thumb_width set above
            $scale = 100 / $w;
            $scropped = $this->resizeThumbnailImage(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '-small.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt(), $imagesource, $w, $h, $x1, $y1, $scale / 2);

            $small->setFile(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '-small' . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt());
            $small->setExt($this->getAvatars(Avatar::AVATAR_LARGE)->getExt());
            $small->setSize(Avatar::AVATAR_SMALL);
            $this->dm->persist($small);
            $this->cropped = true;
        } else
            $this->cropped = false;

        $this->dm->persist($this);
        $this->dm->flush();
        //unlink(__DIR__ . '/../../../../web/tmp/' . $this->getUsername() . '.' . $this->getAvatars(Avatar::AVATAR_LARGE)->getExt());
    }

    //You do not need to alter these functions
    function resizeImage($image, $width, $height, $scale) {
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
        $extension = 'null';
        if ($image_type = exif_imagetype($image)) {
            $extension = image_type_to_extension($image_type, false);
        }
        switch ($extension) {
            case 'png':
                $source = imagecreatefrompng($image);
                break;
            case 'jpeg':
                $source = imagecreatefromjpeg($image);
                break;
            case 'gif':
                $source = imagecreatefromgif($image);
                break;
        }
        imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
        imagejpeg($newImage, $image, 90);
        chmod($image, 0777);
        return $image;
    }

    //You do not need to alter these functions
    function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale) {
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
        $source = imagecreatefromjpeg($image);
        imagecopyresampled($newImage, $source, 0, 0, $start_width, $start_height, $newImageWidth, $newImageHeight, $width, $height);
        imagejpeg($newImage, $thumb_image_name, 90);
        chmod($thumb_image_name, 0777);
        return $thumb_image_name;
    }

    //You do not need to alter these functions
    function getHeight($image) {
        $sizes = getimagesize($image);
        $height = $sizes[1];
        return $height;
    }

    //You do not need to alter these functions
    function getWidth($image) {
        $sizes = getimagesize($image);
        $width = $sizes[0];
        return $width;
    }

    /**
     * Set dob 
     * 
     * @param date $dob 
     */
    public function setDob($dob) {
        $this->dob = $dob;
    }

    public function getPosts() {
        return $this->posts;
    }

    /**
     * Get dob 
     * 
     * @return date $dob 
     */
    public function getDob() {
        return $this->dob;
    }

    /**
     * Set sex 
     * 
     * @param string $sex 
     */
    public function setSex($sex) {
        $this->sex = $sex;
    }

    /**
     * Get sex 
     * 
     * @return string $sex 
     */
    public function getSex() {
        return $this->sex;
    }

    /**
     * Add groups 
     * 
     * @param Vietland\UserBundle\Document\Group $groups 
     */
    public function addGroups(\Vietland\UserBundle\Document\Group $groups) {
        $this->groups[] = $groups;
    }

    /**
     * Get groups 
     * 
     * @return Doctrine\Common\Collections\Collection $groups 
     */
    public function getGroups() {
        return $this->groups;
    }

}

